var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.STOCK15;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/check/check_diff_list';
var querysumurl = config.BASEPATH+'stock/check/check_diff_sum';

var needListRefresh = false;//列表模式
var needSumRefresh = false;//汇总模式
var _height = $(parent).height()-290,_width = $(parent).width()-212;

var fromJsp = $("#fromJsp").val();
if(fromJsp == "check_batch"){
	_height = $(parent).height()-179,_width = $(parent).width()-42;
	$("#btn_close").show();
}
var api = frameElement.api

var showMode = {
	display:function(mode){
		$("#CurrentMode").val(mode);
		$("a[name='mode-btn']").removeClass("on");
		$("#list-grid").hide();
		$("#sum-grid").hide();
		if(mode == 0){
			$("#listBtn").addClass("on");
			$("#list-grid").show();
			showMode.refreshList();
		}else if(mode == 2){
			$("#sumBtn").addClass("on");
			$("#sum-grid").show();
			showMode.refreshSum();
		}
	},
	refreshList:function(){//列表模式刷新数据
		if(!needListRefresh){
    		return;
    	}
    	THISPAGE.reloadData();
    	needListRefresh = false;
	},
	refreshSum:function(){
		if(!needSumRefresh){
			return;
		}
		THISPAGE.reloadSumData();
		needSumRefresh = false;
	},
	refresh:function(){
		var currentMode = $("#CurrentMode").val();
    	if(currentMode == '0'){//列表模式
    		needListRefresh = true;
    		showMode.refreshList();
        	needSumRefresh = true;
    	}else if(currentMode == '2'){//汇总模式
    		needSumRefresh = true;
    		showMode.refreshSum();
    		needListRefresh = true;
    	}
	}
};

var Utils = {
	doQueryDepot : function(){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'stock'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#ba_dp_code").val(selected.dp_code);
					$("#depot_name").val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 280,
		   	height : 320,
		   	top : 50,
		   	left : 250,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : '请选择商品类别!'});
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#pd_tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#pd_bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			cancel:true
		});
	}
};

var handle = {
	formatSubAmount :function(val, opt, row){
		return row.ckl_amount-row.ckl_stock_amount;
	},
	formatSubCostMoney :function(val, opt, row){
		if($.trim(row.ckl_unitprice) == ""){
			return PriceLimit.formatByCost(val);
		}
		return PriceLimit.formatByCost((row.ckl_amount-row.ckl_stock_amount)*row.ckl_unitprice);
	},
	formatSubRetailMoney :function(val, opt, row){
		if($.trim(row.ckl_retailprice) == ""){
			return PriceLimit.formatBySell(val);
		}
		return PriceLimit.formatBySell((row.ckl_amount-row.ckl_stock_amount)*row.ckl_retailprice);
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initSumGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		this.$_loss = $("#loss").cssCheckbox();
		this.$_overflow = $("#overflow").cssCheckbox();
		this.$_flat = $("#flat").cssCheckbox();
		needListRefresh = false;//列表模式
        needSumRefresh = true;//汇总模式
        if(fromJsp != "check_batch"){
        	dateRedioClick("theDate");
        }
	},
	initGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter, align:'center'},
	    	{label:'盘点批次',name: 'ba_number',index: 'ba_number',width:150},
	    	{label:'盘点仓库',name: 'depot_name',index: 'ba_dp_code',width:120},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'',name: 'ckl_pd_code', index: 'ckl_pd_code', width: 100,hidden:true},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'库存数量',name: 'ckl_stock_amount',index: 'ckl_stock_amount',width:60,align:'right'},
	    	{label:'盘点数量',name: 'ckl_amount',index: 'ckl_amount',width:60,align:'right'},
	    	{label:'盈亏数量',name: 'sub_amount',index: '',width:60,align:'right',sortable:false,formatter: handle.formatSubAmount},
	    	{label:'成本价',name: 'ckl_unitprice', index: 'ckl_unitprice', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'ckl_retailprice', index: 'ckl_retailprice', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'盘点金额',name: 'ckl_unitmoney', index: 'ckl_unitmoney', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'差异成本金额',name: 'sub_costmoney', index: '', width: 80,align:'right',sorttype: 'float',formatter: handle.formatSubCostMoney},
	    	{label:'差异零售金额',name: 'sub_retailmoney', index: '', width: 80,align:'right',sorttype: 'float',formatter: handle.formatSubRetailMoney},
	    	{label:'备注',name: 'ckl_remark', index: 'ckl_remark', width: 160}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.DATAROWNUM,//每页条数
			rowList:config.DATAROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'ckl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").jqGrid('getDataIDs');
				var hasBra = false;
				for(var i=0;i < ids.length;i++){
					var rowData = $("#grid").jqGrid("getRowData", ids[i]);
					if(!hasBra && rowData.br_name != null && rowData.br_name != ''){
						hasBra = true;
					}
					if(rowData.sub_amount > 0){
						$("#grid").jqGrid('setRowData', ids[i], false, { color: 'blue' });
					}else if(rowData.sub_amount < 0){
						$("#grid").jqGrid('setRowData', ids[i], false, { color: '#FF0000' });
					}
				}
				if(hasBra){
					$("#grid").setGridParam().showCol("br_name");
				}else{
					$("#grid").setGridParam().hideCol("br_name");
				}
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initSumGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter, align:'center'},
	    	{label:'盘点批次',name: 'ba_number',index: 'ba_number',width:150},
	    	{label:'盘点仓库',name: 'depot_name',index: 'ba_dp_code',width:120},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'',name: 'ckl_pd_code', index: 'ckl_pd_code', width: 100,hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'库存数量',name: 'ckl_stock_amount',index: 'ckl_stock_amount',width:60,align:'right'},
	    	{label:'盘点数量',name: 'ckl_amount',index: 'ckl_amount',width:60,align:'right'},
	    	{label:'盈亏数量',name: 'sub_amount',index: '',width:60,align:'right',sortable:false,formatter: handle.formatSubAmount},
	    	{label:'成本价',name: 'ckl_unitprice', index: 'ckl_unitprice', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'ckl_retailprice', index: 'ckl_retailprice', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'盘点金额',name: 'ckl_unitmoney', index: 'ckl_unitmoney', width: 70,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'差异成本金额',name: 'sub_costmoney', index: '', width: 80,align:'right',sorttype: 'float',formatter: handle.formatSubCostMoney},
	    	{label:'差异零售金额',name: 'sub_retailmoney', index: '', width: 80,align:'right',sorttype: 'float',formatter: handle.formatSubRetailMoney},
	    	{label:'备注',name: 'ckl_remark', index: 'ckl_remark', width: 160}
	    ];
		$('#sumGrid').jqGrid({
            url:querysumurl+'?'+THISPAGE.buildParams(),			
			datatype: 'local',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#sumPage',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.DATAROWNUM,//每页条数
			rowList:config.DATAROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'ckl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#sumGrid").jqGrid('getDataIDs');
				for(var i=0;i < ids.length;i++){
					var rowData = $("#sumGrid").jqGrid("getRowData", ids[i]);
					if(rowData.sub_amount > 0){
						$("#sumGrid").jqGrid('setRowData', ids[i], false, { color: 'blue' });
					}else if(rowData.sub_amount < 0){
						$("#sumGrid").jqGrid('setRowData', ids[i], false, { color: '#FF0000' });
					}
				}
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&ba_dp_code='+$("#ba_dp_code").val();
		params += '&ba_number='+Public.encodeURI($("#ba_number").val());
		params += '&pd_no='+Public.encodeURI($("#pd_no").val());
		params += '&pd_name='+Public.encodeURI($("#pd_name").val());
		params += '&pd_tp_code='+$("#pd_tp_code").val();
		params += '&pd_bd_code='+$("#pd_bd_code").val();
		params += '&loss='+(THISPAGE.$_loss.chkVal().join()? 1 : 0);
		params += '&overflow='+(THISPAGE.$_overflow.chkVal().join()? 1 : 0);
		params += '&flat='+(THISPAGE.$_flat.chkVal().join()? 1 : 0);
		return params;
	},
	reset:function(){
		$("#depot_name").val("");
		$("#ba_dp_code").val("");
		$("#ba_number").val("");
		$("#pd_no").val("");
		$("#pd_name").val("");
		$("#pd_tp_code").val("");
		$("#tp_name").val("");
		$("#pd_bd_code").val("");
		$("#bd_name").val("");
		THISPAGE.$_date.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	reloadSumData:function(){
		var param=THISPAGE.buildParams();
		$("#sumGrid").jqGrid('setGridParam',{datatype:"json",page:1,url:querysumurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			showMode.refresh();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			showMode.refresh();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).ckl_pd_code);
        });
		$('#sumGrid').on('click', '.operating .ui-icon-image', function (e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			viewProductImg($("#sumGrid").jqGrid("getRowData", id).ckl_pd_code);
		});
	}
}
THISPAGE.init();